package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.serve.domain.NursingLevel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        // 判断老人是否已经入住
        // 通过身份证号查询老人
        Elder elder = elderMapper.selectOne(new QueryWrapper<Elder>().eq("id_card_no", dto.getCheckInElderDto().getIdCardNo()));
        if (elder != null) {
            // 判断老人是否已经入住
            if (elder.getBedId() != null) {
                throw new RuntimeException("该老人已经入住");
            }
        }
        // 更新床位的状态  已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 保存或更新老人数据
        elder = insertOrUpdate(dto,bed);
        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();

        // 新增签约办理
        insertContract(contractNo, elder, dto);

        // 新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);

        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), dto);
    }

    @Transactional
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        Long elderId = checkInMapper.selectById(id).getElderId();
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        checkInDetailVo.setCheckInElderVo(getCheckInElderVo(elderId));
        checkInDetailVo.setElderFamilyVoList(setElderFamilyVoList(checkIn));
        checkInDetailVo.setCheckInConfigVo(getCheckInConfigVo(id,checkIn));
        checkInDetailVo.setContract(getContract(elderId));

        return checkInDetailVo;
    }

    
    /**
     * 新增入住配置
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfig.setFeeStartDate(checkInApplyDto.getCheckInConfigDto().getFeeStartDate());
        checkInConfig.setFeeEndDate(checkInApplyDto.getCheckInConfigDto().getFeeEndDate());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0L);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private Elder insertOrUpdate(CheckInApplyDto dto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1L);
        Elder elder1 = elderMapper.selectOne(new QueryWrapper<Elder>().eq("id_card_no", dto.getCheckInElderDto().getIdCardNo()).ne("status", 1));
        if (elder1 != null) {
            // 修改
            elderMapper.updateById(elder);
        } else {
            // 新增
            elderMapper.insert(elder);
        }
        return elder;
    }
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setSignDate(LocalDateTime.now());
        contract.setStatus(Long.valueOf(status));
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    // 查询入住老人信息

    private CheckInElderVo getCheckInElderVo(Long id) {
        Elder elder = elderMapper.selectOne(new QueryWrapper<Elder>().eq("id", id));
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        String idCardNo = elder.getIdCardNo();
        // 提取出生日期（身份证第7-14位是出生日期，格式为YYYYMMDD）
        String birthDateStr = idCardNo.substring(6, 14);
        LocalDateTime birthDate = LocalDateTime.of(
                Integer.parseInt(birthDateStr.substring(0, 4)), // 年
                Integer.parseInt(birthDateStr.substring(4, 6)), // 月
                Integer.parseInt(birthDateStr.substring(6, 8)), // 日
                0, 0, 0
        );

        // 计算年龄
        LocalDateTime now = LocalDateTime.now();
        int age = now.getYear() - birthDate.getYear();
        // 如果今年的生日还没到，年龄减1
        if (now.getMonthValue() < birthDate.getMonthValue() ||
                (now.getMonthValue() == birthDate.getMonthValue() &&
                        now.getDayOfMonth() < birthDate.getDayOfMonth())) {
            age--;
        }
        checkInElderVo.setAge(age);
        return checkInElderVo;
    }

    //获取入住老人亲人信息
    private List<ElderFamilyVo> setElderFamilyVoList(CheckIn checkIn) {
        List<ElderFamilyVo> familyList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        return familyList;
    }

    //查询入住配置
    private CheckInConfigVo getCheckInConfigVo(Long checkInId,CheckIn checkIn) {
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(
                new QueryWrapper<CheckInConfig>().eq("check_in_id", checkInId)
        );
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        return checkInConfigVo;
    }
    //获取合同信息
    private Contract getContract(Long elderId) {
        return contractMapper.selectOne(new QueryWrapper<Contract>().eq("elder_id", elderId));
    }
}
